#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include "Init.hpp"
using namespace std;
extern Log log;
Init init;
class Task
{
public:
    Task()
    {
    }
    Task(int sockfd, const std::string &clientip, uint16_t clientport)
        : _sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {
    }
    ~Task()
    {
    }

    void run()
    {
        char buffer[1024];
        std::string info;
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "server get a message:" << buffer << std::endl;
        }
        else if (n == 0)
        {
            log(Info, "[%s:%d]quit, server close sockfd:%d\n", _clientip.c_str(), _clientport, _sockfd);
        }
        else if (n < 0)
        {
            log(Warning, "read error, clientip:%s, clientport:%d, sockfd:%d\n", _clientip.c_str(), _clientport, _sockfd);
        }
        std::cout << "client#" << buffer << std::endl;
        std::string echo_string = init.Translation(buffer);
        write(_sockfd, echo_string.c_str(), echo_string.size());
        close(_sockfd);
    }

    void operator()()
    {
        run();
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};
